//
//  HMComposePictureView.swift
//  WeiBo
//
//  Created by Feng on 2017/6/13.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

class HMComposePictureView: UICollectionView {

    //定义闭包
    var pictureViewCallBack: (() -> ())?
    
    //设置图片数组
    lazy var pictureArray: [UIImage] =
    {
        let imageArray = [UIImage]()
        
        return imageArray
    }()
    
    //设置选中图片
    var image: UIImage?
    
    //MARK: --显示选中图片的方法
    func showSelectedPicture(image: UIImage)
    {
        if pictureArray.count > 9
        {
            return
        }
        
        self.isHidden = false
        
        pictureArray.append(image)
        
        reloadData()
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        
        let itemMargin: CGFloat = 5
        let itemWidth: CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3
        
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin

        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        //默认隐藏
        self.isHidden = true
        
        dataSource = self
        delegate = self
        
        //注册
        register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: HMComposePictureViewIdentifier)
    }
}

//MARK: --代理方法
extension HMComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate
{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //  如果是0或9张图片，图片数组的原始个数
        if pictureArray.count == 0 || pictureArray.count == 9
        {
            return pictureArray.count
        }
        else
        {
            return pictureArray.count + 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HMComposePictureViewIdentifier, for: indexPath) as! HMComposePictureViewCell

        if indexPath.item == pictureArray.count
        {
            cell.image = nil
        }
        else
        {
            cell.image = pictureArray[indexPath.item]
        }
        
        cell.indexPath = indexPath
        
        cell.deleteButtonCallBack = { (index: Int) -> () in
            
            //删除指定图片
            self.pictureArray.remove(at: index)
            
            self.reloadData()
            
            if self.pictureArray.count == 0
            {
                self.isHidden = true
            }
        }
        
        return cell
    }
    
    //选中item
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //表示选中加号图片
        if indexPath.item == pictureArray.count
        {
            //执行回调
            pictureViewCallBack?()
        }
    }
    
}

//MARK: --自定义cell
class HMComposePictureViewCell: UICollectionViewCell
{
    //定义删除按钮闭包
    var deleteButtonCallBack: ((Int) -> ())?
    
    //MARK: --懒加载控件
    private lazy var deleteButton: UIButton =
    {
        let button = UIButton()
        button.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        
        return button
    }()
    
    private lazy var imageView: UIImageView =
    {
        let imgView = UIImageView()
        
        return imgView
    }()
    
    //indexPath
    var indexPath: IndexPath?
    
    //显示图片
    var image: UIImage?
    {
        didSet {
            if image == nil
            {
                imageView.image = UIImage(named: "compose_pic_add")
                deleteButton.isHidden = true
            }
            else
            {
                imageView.image = image
                deleteButton.isHidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI()
    {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
    }
    
    //MARK: --删除按钮监听方法
    @objc private func deleteButtonAction()
    {
        if let currentIndexPath = indexPath
        {
            let item = currentIndexPath.item
            //执行回调
            deleteButtonCallBack?(item)
        }
    }
}
